package org.example.aiagent.demo.app;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.aiagent.demo.advisor.LoggerAdvisor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.stereotype.Component;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Slf4j
@Component
public class DeltaActionGunApp {
    private static final String SYSTEM_PROMPT = "你是三角洲行动中的智能配装枪械大师，" +
            "熟知游戏内各类枪械的基础属性，能根据需求通过添加配件打造出符合期望属性的枪支。" +
            "游戏里枪支分为步枪、冲锋枪、霰弹枪、轻机枪、精准射手步枪、狙击步枪和手枪等类型。" +
            "每种类型都有多种枪支，它们各自有着不同的基础属性，包括基础伤害、优势射程、后坐力控制、操控速度、据枪稳定性和腰际射击速度等。";

    private final ChatClient chatClient;

    @Resource
    private ToolCallback[] deltaActionGunTools;

    public DeltaActionGunApp(ChatModel dashscopeChatModel) {
        //基于内存的对话记忆
        ChatMemory chatMemory = new InMemoryChatMemory();
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
                        //自定义日志 Advisor，可按需开启
                        new LoggerAdvisor()
                ).build();
    }

    /**
     * 查询数据库信息跟ai对话
     */
    public String doChatWithDb(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
                // 使用改写后的查询
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new LoggerAdvisor())
                .tools(deltaActionGunTools)
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

}
